import sys
import json
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets

import random
import string


class Dail:
    def __init__(self):
        self.dial_list = []

    def add(self, username, phone_number):
        self.dial_list.append((username, phone_number))
        return self.dial_list

    def delete(self, serial_number):
        print(self.dial_list)
        if len(self.dial_list) == 0:
            return self.dial_list
        else:
            self.dial_list.remove(self.dial_list[serial_number])
            return self.dial_list

    def up(self, serial_number):
        print (self.dial_list)
        if serial_number == 0:
            return self.dial_list
        else:
            self.dial_list[serial_number - 1], self.dial_list[serial_number] = self.dial_list[serial_number], \
                                                                               self.dial_list[serial_number - 1]
            return self.dial_list

    def down(self, serial_number):
        print(self.dial_list)
        if serial_number == len(self.dial_list)-1:
            return self.dial_list
        else:
            self.dial_list[serial_number], self.dial_list[serial_number + 1] = self.dial_list[serial_number + 1], \
                                                                               self.dial_list[serial_number]
            return self.dial_list


class ItemWidget(QWidget):
    delete_item = pyqtSignal(QListWidgetItem)
    up_item = pyqtSignal(QListWidgetItem)
    down_item = pyqtSignal(QListWidgetItem)

    def __init__(self, name,phone, item, *args, **kwargs):
        super(ItemWidget, self).__init__(*args, **kwargs)
        self._item = item  # 保留list item的对象引用

        self.layoutmain = QVBoxLayout(self)
        self.up_lay = QHBoxLayout()
        self.down_lay = QHBoxLayout()
        self.layoutmain.addLayout(self.up_lay)
        self.layoutmain.addLayout(self.down_lay)

        self.up_lay.addWidget(QLabel(name))
        self.up_lay.addWidget(QPushButton('up', self, clicked=self.sent_up_item))
        self.up_lay.addWidget(QPushButton('down', self, clicked=self.sent_down_item))
        self.up_lay.addWidget(QPushButton('x', self, clicked=self.sent_delete_item))

        self.down_lay.addWidget(QLabel(phone))

    def sent_up_item(self):
        self.up_item.emit(self._item)

    def sent_down_item(self):
        self.down_item.emit(self._item)

    def sent_delete_item(self):
        self.delete_item.emit(self._item)

    def sizeHint(self):
        # 决定item的高度
        return QSize(200, 100)


class Ui_MainWindow(object):
    """
    自动生成的代码, 请不要修改
    """
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(455, 357)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(10, 10, 341, 341))
        self.listWidget.setObjectName("listWidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(360, 10, 81, 31))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "添加数据"))


class Windows(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(Windows, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.append_message)
        self.dial_list = Dail()


    def show_message(self,message):
        print (message)

    def append_message(self):
        def ranstr(num):
            salt = ''.join(random.sample(string.ascii_letters + string.digits, num))
            return salt
        # salt = ranstr(6)
        # print(salt)

        # self.dial_list.add('naaa', '0134')
        # self.dial_list.add('naaa', '446')
        # self.dial_list.add('sai', '4561')
        self.doClearItem()
        self.dial_list.add(ranstr(6), ranstr(4))
        self.append_item()

    def append_item(self):
        for i in self.dial_list.dial_list:
            self.show_item(i[0],i[1])

    def show_item(self,name,phone):

        item = QListWidgetItem()  # 创建QListWidgetItem对象

        item.setSizeHint(QSize(200, 100))  # 设置QListWidgetItem大小
        widget = ItemWidget('item: {}'.format(name),phone, item, self.listWidget)  # 调用上面的函数获取对应
        widget.delete_item.connect(self.delete)
        widget.up_item.connect(self.up)
        widget.down_item.connect(self.down)


        self.listWidget.addItem(item)  # 添加item
        self.listWidget.setItemWidget(item, widget)  # 为item设置widget
        #self.listWidget.itemClicked.connect(self.show_message)

    def up(self,item):
        row = self.listWidget.indexFromItem(item).row()
        self.dial_list.up(row)
        self.doClearItem()  # 清空
        self.append_item()  # 再次添加
        print (self.dial_list.dial_list)

    def down(self,item):
        row = self.listWidget.indexFromItem(item).row()
        self.dial_list.down(row)
        self.doClearItem()  # 清空
        self.append_item()  # 再次添加
        print(self.dial_list.dial_list)

    def delete(self,item):
        row = self.listWidget.indexFromItem(item).row()
        self.dial_list.delete(row)
        self.doClearItem()  # 清空
        self.append_item()  # 再次添加
        print(self.dial_list.dial_list)

    def doClearItem(self):
        # 清空所有Item
        for _ in range(self.listWidget.count()):
            # 删除item
            # 一直是0的原因是一直从第一行删,删掉第一行后第二行变成了第一行
            # 这个和删除list [] 里的数据是一个道理
            item = self.listWidget.takeItem(0)
            # 删除widget
            self.listWidget.removeItemWidget(item)
            del item

app = QtWidgets.QApplication(sys.argv)
windows = Windows()
windows.show()
sys.exit(app.exec_())
